package com.neusoft.jxc.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.jxc.bean.PssException;
import com.neusoft.jxc.bean.SysUser;
import com.neusoft.jxc.mapper.SysUserMapper;
import com.neusoft.jxc.service.SysUserService;
import com.neusoft.jxc.util.PasswordUtils;

/**
 * 使用@Service把service实现类配置为一个spring的组件；@Service表示一个服务层的组件
 * 
 * @Transactional 配置spring事务管理切面
 * 
 * @author chens
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserServiceImpl extends AbstractServiceImpl<SysUser> implements SysUserService {

	@Autowired
	private SysUserMapper userMapper;

	@Override
	public SysUser login(SysUser user) throws PssException {

		SysUser user2 = userMapper.login(user);
		//使用明文密码与随机密码进行加密计算， 再与数据库的密码进行比较进行密码校验
		boolean ret = PasswordUtils.matches(user2.getSalt(), user.getPassword(), user2.getPassword());

		if (ret) {
			return user2;
		} else {
			// 密码验证失败，返回null表示登录失败
			return null;
		}

	}

	@Override
	public boolean add(SysUser param) throws PssException {
		// 生成随机的盐值- 随机动态密码
		String salt = PasswordUtils.getSalt();
		String encodePassword = PasswordUtils.encode(param.getPassword(), salt);
		// 保存随机密码和加密密码
		param.setSalt(salt);
		param.setPassword(encodePassword);

		boolean ret = userMapper.add(param);

		return ret;

	}

	@Override
	public boolean edit(SysUser param) throws PssException {
		// 生成随机的盐值- 随机动态密码
		String salt = PasswordUtils.getSalt();
		String encodePassword = PasswordUtils.encode(param.getPassword(), salt);
		// 保存随机密码和加密密码
		param.setSalt(salt);
		param.setPassword(encodePassword);

		boolean ret = userMapper.edit(param);

		return ret;
	}

}
